﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "subject.h"

#define SUBJECT_TYPE_DANXUAN QStringLiteral("单选题")
#define SUBJECT_TYPE_DUOXUAN QStringLiteral("多选题")
#define SUBJECT_TYPE_PANDUAN QStringLiteral("判断题")

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 创建 QStandardItemModel
    this->model = new QStandardItemModel(0, 4, this->ui->subjectTableView); // 0 行, 4 列

    // 设置表头
    QStringList headers;
    headers << QStringLiteral("题号") << QStringLiteral("题目类型") << QStringLiteral("题目内容") << QStringLiteral("题目答案");
    model->setHorizontalHeaderLabels(headers);
    // 设置 QTableView 的模型
    this->ui->subjectTableView->setModel(model);

    // 设置列宽自动调整（可选）
    this->ui->subjectTableView->resizeColumnsToContents();

    // 或者
    this->ui->subjectTableView->setColumnWidth(0, 50); // 设置第一列的宽度为 50
    this->ui->subjectTableView->setColumnWidth(1, 80); // 设置第二列的宽度为 50
    this->ui->subjectTableView->setColumnWidth(2, 400); // 设置第二列的宽度为 400
    this->ui->subjectTableView->setColumnWidth(3, 100); // 设置第二列的宽度为 100
    // ... 为其他列设置宽度

    // 如果想要固定列宽并允许用户调整
    this->ui->subjectTableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed); // 固定第1列宽度
    this->ui->subjectTableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed); // 固定第2列宽度
    this->ui->subjectTableView->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Interactive); // 第3列允许用户调整
    this->ui->subjectTableView->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Fixed); // 固定第4列宽度

    // 窗口底部信息
    this->ui->subjectTextLabel->setText(QStringLiteral("点击【导入】按钮选择txt文本文件进行导入！"));
    this->ui->subjectTextLabel->setStyleSheet("color:#F60;");

    // 事件绑定
    this->initSlots();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initSlots(){
     connect(this->ui->importSubject,SIGNAL(clicked()),SLOT(importText()));
     connect(this->ui->exportSubjectToExel,SIGNAL(clicked()),SLOT(exportSubjectToExel()));
     connect(this->ui->clearSubject,SIGNAL(clicked()),SLOT(clearSubject()));
}

void MainWindow::clearSubject(){
    this->ui->importTextLineEdit->setText("");
    // 清除所有行
    this->model->removeRows(0, model->rowCount());

    // 刷新视图（在某些情况下可能需要，但通常 removeRows 会自动触发）
//    this->ui->subjectTableView->viewport()->update();
    subjectList.clear();
}

void MainWindow::importText(){
    QString fileName = QFileDialog::getOpenFileName(this, QStringLiteral("选择txt文件"), QStringLiteral("C:/Users/zb/Desktop"), QStringLiteral("txt(*.txt)"));
    if (!fileName.isEmpty()) {
//        importToExcel(fileName);
//         QMessageBox::information(nullptr, QStringLiteral("提示"), fileName);
         this->ui->importTextLineEdit->setText(fileName);
         QFile file(fileName);
         if (!file.open(QIODevice::ReadOnly)) {
            QMessageBox::critical(this, QStringLiteral("提示"), QStringLiteral("文件不能打开: ") + file.errorString());
            return;
         }

         QTextStream in(&file);
         in.setCodec("UTF-8");
         QList<QString> textList;
         while (!in.atEnd()) {
             QString line = in.readLine();
             // 处理读取的每一行，例如显示在文本编辑器中
             // ui->textEdit->append(line);
             if(line != nullptr && line != ""){
                  textList << line;
             }
         }
         file.close();

         // 清除所有行
         this->model->removeRows(0, model->rowCount());

         // 刷新视图（在某些情况下可能需要，但通常 removeRows 会自动触发）
         this->ui->subjectTableView->viewport()->update();


         // 解析转化试题对象
         this->subjectList  = this->parseTextList(&textList);


         // 统计题目数量
         int type1=0,type2=0,type3=0;
         for(int i=0; i< this->subjectList.size(); i++){
             Subject *subject= this->subjectList.at(i);

             // 添加数据到表格
             this->addSubjectToTable(subject);

             if(subject->subType == "1"){
                 type1++;
             }
             if(subject->subType == "2"){
                 type2++;
             }
             if(subject->subType == "3"){
                 type3++;
             }
         }

//         // 设置列宽自动调整（可选）
//         this->ui->subjectTableView->resizeColumnsToContents();
//         // 或者
//         this->ui->subjectTableView->setColumnWidth(0, 50); // 设置第一列的宽度为 50
//         this->ui->subjectTableView->setColumnWidth(1, 80); // 设置第二列的宽度为 50
//         this->ui->subjectTableView->setColumnWidth(2, 400); // 设置第二列的宽度为 100
//         this->ui->subjectTableView->setColumnWidth(3, 100); // 设置第二列的宽度为 100

         // 窗口底部信息
         qDebug().noquote() << QStringLiteral("-----------------------------------------------------");
         qDebug().noquote() << SUBJECT_TYPE_DANXUAN << type1 << QStringLiteral("道;");
         qDebug().noquote() << SUBJECT_TYPE_DUOXUAN << type2 << QStringLiteral("道;");
         qDebug().noquote() << SUBJECT_TYPE_PANDUAN << type3 << QStringLiteral("道;");
         this->ui->subjectTextLabel->
                 setText(SUBJECT_TYPE_DANXUAN + QString::number(type1) + QStringLiteral("道;")+ "  "+
                         SUBJECT_TYPE_DUOXUAN + QString::number(type2) + QStringLiteral("道;")+"  "+
                         SUBJECT_TYPE_PANDUAN + QString::number(type3) + QStringLiteral("道;")+"  "+
                         QStringLiteral("一共")+ QString::number(subjectList.size())+  QStringLiteral("道题！"));
         this->ui->subjectTextLabel->setStyleSheet("color:black;");
         qDebug().noquote() << QStringLiteral("-----------------------------------------------------");
    } else {
         QMessageBox::critical(nullptr, QStringLiteral("提示"), QStringLiteral("文件不能为空"));
    }
}



QList<Subject*> MainWindow::parseTextList(QList<QString> *textList){
    QList<Subject*> result;
    if(textList->isEmpty() || textList->size() == 0){
        qDebug() << "解析题目txt为空！";
        return result;
    }

    // 当前题型
    QString subType = "1";
    // 当前题号码
    int subNum = 0;
//    Subject subject;
    //当前是解析的是题干还是选项
    // 1 ：题干  2：选项
    QString lineType = "1";
    // 上一行
    QString preLine = "";
    // 上一个题型
    QString preSubType = "1";
    // 上一个题号
    QString preSubNum = "0";
    // 上一个题干
    QString preSubContent = "";
    // 上一个题目选项
    QString preOptionContenet = "";
    // 是否开始题目行
    bool isStartSubject = false;
    // 添加一道题
    Subject *subject;
    for(int i = 0; i < textList->size(); i++){
        QString line = textList->at(i);
        // 下一行
        QString nextLine = nullptr;
        if(i < textList->size()-1){
            nextLine = textList->at(i+1);
        }
        // 空的忽略
        if(line == nullptr || line.isEmpty()){
            continue;
        }
        line = line.trimmed();

        // 判断是否是大题
        if(!isStartSubject && startsWithChinesePrefix(line)){
            isStartSubject = true;
//            qDebug() << "startsWithChinesePrefix is true";
        }
        if(isStartSubject){
            // 判断题型
            if(this->startsWithChinesePrefix(line) && line.contains(SUBJECT_TYPE_DANXUAN)){
                preSubNum = "0";
                subType = "1";
                continue;
            }
            if(this->startsWithChinesePrefix(line) &&  line.contains(SUBJECT_TYPE_DUOXUAN)){
                preSubNum = "0";
                subType = "2";
                continue;
            }
            if(this->startsWithChinesePrefix(line) &&  line.contains(SUBJECT_TYPE_PANDUAN)){
                preSubNum = "0";
                subType = "3";
                continue;
            }

//             qDebug() << "subType:" << subType;
            // 需要判断当前行是题干还是选项，还是换行接上一行的
            if(this->startsWithDigit(line)){
//                qDebug() << line << "subNum:" << subNum;
                // 本行是题干开头
                lineType = "1";

                // 题干为空才是新的一道题目
                if(preSubContent == ""){
                    // 添加一道题
                    subject = new Subject();

                    subNum +=1;

                    subject->subType = subType;
                    subject->subTypeName = subType == "1"?SUBJECT_TYPE_DANXUAN:(subType == "2"?SUBJECT_TYPE_DUOXUAN:(subType == "3"?SUBJECT_TYPE_PANDUAN:subType));

                    // 题干和答案在一行
                    QString subjectNum;
                    QList<QString> subjectNumList = this->getSubjectNum(line);
                    if(!subjectNumList.isEmpty() && subjectNumList.size()>0){
                        subjectNum = subjectNumList.at(0);
                    }
                    subject->subNum = subjectNum;
                }

                if(this->isAnswer(line, subType)){
                    // 答案
                    QString answer;
                    QList<QString> answerList = this->getAnswerContents(line, subType);
                    if(answerList.size()>0){
                        answer = answerList.at(0);
                    }
                    subject->subAnswer = this->getAnswerBySubType(answer,subType);
                    QString lineSubContent = line.replace(answer,"")
                            .replace("(","")
                            .replace(")","")
                            .replace(QStringLiteral("（"),"")
                            .replace(QStringLiteral("）"),"")
                            .replace(subject->subNum,"")
//                            .replaceFirst(".","")
                            ;
                    if(preSubContent == ""){
                        subject->subContent = this->replaceFirstDot(lineSubContent, "").trimmed();
                    } else {
                        subject->subContent = preSubContent.trimmed() + lineSubContent.trimmed();
                    }

                    // 上一个题号
                    preSubNum = subject->subNum;
                    // 上一个题型
                    preSubType = subType;
                    result.append(subject);

                    preSubContent = "";
                }
                else {
                    // 本行答案和题干不在一行
                    if(preSubContent == ""){
                        preSubContent =  line.replace(subject->subNum,"");
                        preSubContent = this->replaceFirstDot(preSubContent, "");
                    } else {
                        preSubContent += line;
                    }

                }

            } else if(this->isSubOption(line)){
                // 本行是选项开头
                lineType = "2"; // 本行是选项
                QString optionType = "";// 选项
                QString optionContenet = "";
                QList<QString> subjectOptionList = this->getSubjectOption(line);
                if(subjectOptionList.size()>0){
                    optionType = subjectOptionList.at(0);
                }
                optionContenet = line.replace(optionType,"")
//                        .replaceFirst(".", "")
                        ;
                if(nextLine != nullptr &&
                        (startsWithChinesePrefix(nextLine) || startsWithDigit(nextLine) || isSubOption(nextLine))){
                    optionContenet = this->replaceFirstDot(optionContenet, "");
                    optionContenet = optionContenet.trimmed();
                    subject->optionList.append(optionContenet);
                    preOptionContenet = "";
                } else {
                    preOptionContenet = optionContenet;
                }
            }
            else {
                // 含有结答案
                if(this->isAnswer(line, subType)){
                    QString answer = "";
                    QList<QString> answerList = this->getAnswerContents(line, subType);
                    if(answerList.size()>0){
                        answer = answerList.at(0);
                    }
                    subject->subAnswer = getAnswerBySubType(answer,subType);
                    QString lineSubContent = line.replace(answer,"")
                            .replace("(","")
                            .replace(")","")
                            .replace(QStringLiteral("（"),"")
                            .replace(QStringLiteral("）"),"");
                    preSubContent +=lineSubContent;

                    subject->subContent = preSubContent.trimmed();
                    // 上一个题号
                    preSubNum = subject->subNum;
                    // 上一个题型
                    preSubType = subType;
                    result.append(subject);
                    preSubContent = "";
                } else {
                    if("1" == lineType){
                        // 题干
                        preSubContent += line;
                    }
                    if("2" == lineType){
                        // 题目选项
                        preOptionContenet += line;
                        if(nextLine != nullptr &&
                                (startsWithChinesePrefix(nextLine) || startsWithDigit(nextLine) || isSubOption(nextLine))) {
                            preOptionContenet = this->replaceFirstDot(preOptionContenet, "");
                            preOptionContenet = preOptionContenet.trimmed();
                            subject->optionList.append(preOptionContenet);
                            preOptionContenet = "";
                        }
                    }
                }
            }
            preLine = line;
        }

    }
    return result;
}

void MainWindow::addSubjectToTable(Subject *subject){
    qDebug().noquote() << subject->getSubNum() << subject->subContent << subject->subAnswer;
    // 添加数据
    QList<QStandardItem*> row;
    QStandardItem* subNumItem = new QStandardItem(subject->subNum);
    subNumItem->setTextAlignment(Qt::AlignCenter);
    row.append(subNumItem);
    QStandardItem* subTypeNameItem = new QStandardItem(subject->subTypeName);
    subTypeNameItem->setTextAlignment(Qt::AlignCenter);
    row.append(subTypeNameItem);
    QStandardItem* subContentItem = new QStandardItem(subject->subContent);
//    subContentItem->setTextAlignment(Qt::AlignCenter);
    row.append(subContentItem);
    QStandardItem* subAnswerItem = new QStandardItem(subject->subAnswer);
    subAnswerItem->setTextAlignment(Qt::AlignCenter);
    row.append(subAnswerItem);
//    row  << new QStandardItem(subject->subNum)
//         << new QStandardItem(subject->subTypeName)
//         << new QStandardItem(subject->subContent)
//         << new QStandardItem(subject->subAnswer);

    this->model->appendRow(row);
//    this->ui->subjectTableView->scrollToBottom();

    // 刷新视图（在某些情况下可能需要，但通常 removeRows 会自动触发）
//    this->ui->subjectTableView->viewport()->update();
//    QThread::msleep(0);
//    // 例如选择第一行
//    QItemSelectionModel *selectionModel = this->ui->subjectTableView->selectionModel();
//    selectionModel->select(model->index(subNum-1, 0), QItemSelectionModel::Select | QItemSelectionModel::Rows);
//    // 滚动到选中的行
//    this->ui->subjectTableView->scrollTo(selectionModel->currentIndex());
}


// 替换掉第一个.
QString MainWindow::replaceFirstDot(const QString &str, const QString &replacement) {
    int dotIndex = str.indexOf('.');
    if (dotIndex != -1) {
        // 找到点号，分割字符串并替换
        QString leftPart = str.left(dotIndex);
        QString rightPart = str.mid(dotIndex + 1);
        return leftPart + replacement + rightPart;
    }
    // 如果没有找到点号，返回原字符串
    return str;
}


// 根据题目类型处理题目答案
QString MainWindow::getAnswerBySubType(QString &answer, QString &subType) {
    if("1" == subType){
        return answer;
    } else if("2" == subType){
        return insertCommaBetweenChars(answer);
    } else if("3" == subType){
        return (QStringLiteral("√") == answer ? "A":  (QStringLiteral("×") == answer ? "B": answer));
    } else {
        return answer;
    }
}

// 多选答案中间添加逗号
QString MainWindow::insertCommaBetweenChars(QString &str) {
    if (str == nullptr || str.isEmpty()) {
        return str;
    }

    // 使用StringBuilder来构建结果字符串，因为它比String更适合字符串的修改
    QString *sb = new QString();

    // 遍历字符串的每个字符，除了最后一个
    for (int i = 0; i < str.length() - 1; i++) {
        sb->append(str.at(i));
        sb->append(",");
    }

    // 添加最后一个字符
    sb->append(str.at(str.length() - 1));

    // 将StringBuilder转换为String并返回
    return *sb;
}

bool MainWindow::startsWithChinesePrefix(QString &str) {
        // 检查字符串是否为空或null
        if (str.isEmpty()) {
            return false;
        }
        // 检查是否以“一”、“二”、“三”开头
//        QString prefixes[] = {"一", "二", "三", "四","五", "六", "七", "八", "九", "十"};
        QString prefixes[] = {QStringLiteral("一"), QStringLiteral("二"), QStringLiteral("三"), QStringLiteral("四"),QStringLiteral("五"), QStringLiteral("六"), QStringLiteral("七"), QStringLiteral("八"), QStringLiteral("九"),QStringLiteral("十")};
        for (QString &prefix : prefixes) {
            if (str.startsWith(prefix)) {
                return true;
            }
        }
        // 如果不是以这些中文字符开头，则返回false
        return false;
}

// 数字开头的为题干
bool MainWindow::startsWithDigit(QString &str) {
   // 检查字符串是否为空或null
   if (str == nullptr || str.isEmpty()) {
       return false;
   }
   // 检查第一个字符是否是数字
   bool fisrtIsNum = str.at(0).isDigit();
   return fisrtIsNum && isNumeric(str);
}

// 判断是否是数字+.开头的字符串
bool MainWindow::isNumeric(QString &str) {
   if (str == nullptr || str.isEmpty()) {
       return false;
   }
   QRegularExpression re("^([0-9]+)\\.");
   QRegularExpressionMatch match = re.match(str);
   return  match.hasMatch();
}

// 获取题目号
QList<QString> MainWindow::getSubjectNum(QString &text){
    QList<QString> contents;
    if(text == nullptr || text.isEmpty()){
        return contents;
    }
    QRegularExpression regex("([0-9]+)\\.");
    QRegularExpressionMatchIterator it = regex.globalMatch(text);

    while (it.hasNext()) {
        QRegularExpressionMatch match = it.next();
        if (match.hasMatch()) {
//            QString text = QStringLiteral("56. 脚手架在土木建筑工程1.2中的作用是什么（C）");
//            QString firstChar = match.captured(0); // 获取匹配到的字符 56.
             contents.append(match.captured(match.lastCapturedIndex())); // 直接添加捕获的数字部分 56
            break; // 找到后退出循环
        }
    }
    return contents;
}


// 判断是否是选项
bool MainWindow::isSubOption(QString &text) {
    if(text == nullptr || text.isEmpty()){
        return false;
    }
    QRegularExpression re("^([A-Z]+)\\.");
    QRegularExpressionMatch match = re.match(text);
    return  match.hasMatch();
}

QList<QString> MainWindow::getSubjectOption(QString &text) {
    QList<QString> contents;
    if(text == nullptr || text.isEmpty()){
        return contents;
    }
    QRegularExpression regex("^([A-Z]+)\\.");
    QRegularExpressionMatchIterator it = regex.globalMatch(text);
    while (it.hasNext()) {
        QRegularExpressionMatch match = it.next();
        if (match.hasMatch()) {
//            QString firstChar = match.captured(0); // 获取匹配到的字符 56.
            contents.append(match.captured(match.lastCapturedIndex())); // 直接添加捕获的数字部分 56
            break; // 找到后退出循环
        }
    }
    return contents;
}


// 判断是否是答案行
bool MainWindow::isAnswer(QString &text, QString &subType) {
    if(text == nullptr || text.isEmpty()){
        return false;
    }
    QRegularExpression regex(QStringLiteral("(?:（([A-Z]+)）$)|(?:\\(([A-Z]+)\\)$)"));
    if("3" == subType){
        regex.setPattern(QStringLiteral("(?:（([^）]+)）$)|(?:\\(([^)]+)\\)$)"));
    }
    QRegularExpressionMatch match = regex.match(text);
    return  match.hasMatch();
}


// 获取答案选项
QList<QString> MainWindow::getAnswerContents(QString &text, QString &subType) {
    QList<QString> contents;
    if(text == nullptr || text.isEmpty()){
        return contents;
    }
    QRegularExpression regex(QStringLiteral("(?:（([A-Z]+)）$)|(?:\\(([A-Z]+)\\)$)"));
    if("3" == subType){
        regex.setPattern(QStringLiteral("(?:（([^）]+)）$)|(?:\\(([^)]+)\\)$)"));
    }
    QRegularExpressionMatchIterator it = regex.globalMatch(text);
    while (it.hasNext()) {
        QRegularExpressionMatch match = it.next();
        if (match.hasMatch()) {
            contents.append(match.captured(match.lastCapturedIndex())); // 直接添加捕获的数字部分 56
            break; // 找到后退出循环
        }
        //        if (match.captured(1)) {
        //            // 匹配到的是中文圆括号内的内容
        //            contents.append(match.captured(1));
        //        } else if (match.captured(2).isValid()) {
        //            // 匹配到的是英文圆括号内的内容
        //            contents.append(match.captured(2));
        //        }
    }
    return contents;
}


// 导出试题表格
void MainWindow::exportSubjectToExel(){
    if(model->rowCount() > 0){
        //获取保存路径
        QString filePath=QFileDialog::getSaveFileName(this,tr("Save Excel File"),QStringLiteral("C:/Users/zb/Desktop"),tr("Excel Files (*.xlsx)"));
        if(!filePath.isEmpty()){
            QXlsx::Document xlsx;
            int row = 1;
//            QXlsx::Format formatTitle;
//            formatTitle.setFontBold(true);
//            formatTitle.setFontColor(QColor(Qt::black));
//            formatTitle.setFontSize(20);
//            formatTitle.setBorderStyle(QXlsx::Format::BorderThin);
//            formatTitle.setPatternBackgroundColor(Qt::lightGray);
//            formatTitle.setFillPattern(QXlsx::Format::PatternSolid);
//            formatTitle.setHorizontalAlignment(QXlsx::Format::AlignHCenter);
//            xlsx.mergeCells(QXlsx::CellRange(1, 1, 1, 7), formatTitle);
//            xlsx.write(1, 1, QStringLiteral("仓库订单详情表"));

            xlsx.setColumnWidth(1,15);
            xlsx.setColumnWidth(2,50);
            xlsx.setColumnWidth(3,40);
            xlsx.setColumnWidth(4,20);
            xlsx.setColumnWidth(5,30);
            xlsx.setColumnWidth(6,20);
            xlsx.setColumnWidth(7,20);
            xlsx.setColumnWidth(8,20);
            xlsx.setColumnWidth(9,20);
            xlsx.setColumnWidth(10,20);
            xlsx.setColumnWidth(11,20);

            // 表头
            QXlsx::Format format1;
            format1.setFontBold(false);
            format1.setFontSize(14);
            format1.setFontColor(QColor(Qt::black));
            format1.setBorderStyle(QXlsx::Format::BorderThin);
            format1.setPatternBackgroundColor(Qt::darkGray);
            format1.setVerticalAlignment(QXlsx::Format::AlignVCenter);
            format1.setHorizontalAlignment(QXlsx::Format::AlignHCenter);
            // 表头
            QString headers[] = {QStringLiteral("序号"), QStringLiteral("题目内容"), QStringLiteral("题目类型(1单选/2多选/3判断)"), QStringLiteral("题目解析"),
                                 QStringLiteral("正确选项(英文逗号)"), QStringLiteral("分值"), QStringLiteral("选项A内容"), QStringLiteral("选项B内容"),
                                 QStringLiteral("选项C内容"),QStringLiteral("选项D内容"),QStringLiteral("...(依次增加)")};
            int count = sizeof(headers)/sizeof(headers[0]);
            for(int i=0; i< count; i++){
                xlsx.write(row, i+1, headers[i], format1);
            }


            // 数据
            if(!this->subjectList.isEmpty() && this->subjectList.size() >0){
                QXlsx::Format format2;
                format2.setVerticalAlignment(QXlsx::Format::AlignVCenter);
                format2.setHorizontalAlignment(QXlsx::Format::AlignHCenter);
                format2.setFontBold(false);
                format2.setFontColor(QColor(Qt::black));
                format2.setBorderStyle(QXlsx::Format::BorderThin);
                format2.setFont(QStringLiteral("宋体"));
                row++;
                for(int i=0; i< this->subjectList.size(); i++){
                    Subject *subject = this->subjectList.at(i);
//                    qDebug().noquote() << subject->subNum << subject->subContent << subject->subAnswer;
                    xlsx.write(row, 1, subject->subNum, format2);
                    xlsx.write(row, 2, subject->subContent, format2);
                    xlsx.write(row, 3, subject->subType, format2);
                    xlsx.write(row, 4, QStringLiteral(""), format2);
//                    QString answer = getAnswerBySubType(subject->subAnswer, subject->subType);
                    xlsx.write(row, 5, subject->subAnswer, format2);
                    xlsx.write(row, 6, QStringLiteral(""), format2);
                    QList<QString> optionList = subject->optionList;
                    if(!optionList.isEmpty()){
                        for(int j=0; j<optionList.size();j++){
                            xlsx.write(row, 7+j, optionList.at(j), format2);
                        }
                    } else {
                        for(int j=0; j<4;j++){
                            xlsx.write(row, 7+j, "", format2);
                        }
                    }
                    row++;
                }
            }



//            int r = ui->tableView_4->model()->rowCount();
//            QXlsx::Format format3;
//            format3.setFontBold(false);
//            format3.setFontColor(QColor(Qt::black));
//            format3.setFont(QStringLiteral("SimSun"));
//            xlsx.write(1, 8, QDateTime::currentDateTime().toString("M/d hh:mm"),format3);
//            xlsx.setColumnWidth(8,15);

//            for (int col = 1; col <= 7; col++)
//            {
//              for (int row = 3; row <= r+2; row++)
//              {
//                xlsx.write(row, col, model4->data(model4->index(row-3,col-1)), format2);
//              }
//            }
            // 设置文件路径
//            xlsx.saveAs(QStringLiteral("仓库订单详情表.xlsx"));
//            QDesktopServices::openUrl(QUrl::fromLocalFile(QFileInfo(QStringLiteral("仓库订单详情表.xlsx")).absoluteFilePath()));
            xlsx.saveAs(filePath);
            QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("导出成功啦！！！"));
            qDebug().noquote() << QStringLiteral("导出成功啦！！！");
            // 打开文件
            QDesktopServices::openUrl(QUrl::fromLocalFile(QFileInfo(filePath).absoluteFilePath()));
        } else {
            QMessageBox::critical(nullptr, QStringLiteral("提示"), QStringLiteral("导出文件名不能为空！"));
        }
    } else {
        QMessageBox::critical(nullptr, QStringLiteral("提示"), QStringLiteral("待导出的数据为空"));
    }
}



// 导出表格中的内容
void MainWindow::exportTabelViewToExel(){
    if(model->rowCount() > 0){
        //获取保存路径
        QString filePath=QFileDialog::getSaveFileName(this,tr("Save"),QStringLiteral("C:/Users/zb/Desktop"),tr(" (*.xlsx)"));
        if(!filePath.isEmpty()){
            QAxObject *excel = new QAxObject(this);
            //连接Excel控件
            excel->setControl("Excel.Application");
            //不显示窗体
            excel->dynamicCall("SetVisible (bool Visible)","false");
            //不显示任何警告信息。如果为true那么在关闭是会出现类似“文件已修改，是否保存”的提示
            excel->setProperty("DisplayAlerts", false);
            //获取工作簿集合
            QAxObject *workbooks = excel->querySubObject("WorkBooks");
            //新建一个工作簿
            workbooks->dynamicCall("Add");
            //获取当前工作簿
            QAxObject *workbook = excel->querySubObject("ActiveWorkBook");
            //获取工作表集合
            QAxObject *worksheets = workbook->querySubObject("Sheets");
            //获取工作表集合的工作表1，即sheet1
            QAxObject *worksheet = worksheets->querySubObject("Item(int)",1);
            //设置表头值
            for(int i=1;i<model->columnCount()+1;i++)
            {
                //设置设置某行某列
                QAxObject *Range = worksheet->querySubObject("Cells(int,int)", 1, i);
                Range->dynamicCall("SetValue(const QString &)",model->horizontalHeaderItem(i-1)->text());
            }
            //设置表格数据
            for(int i = 1;i<model->rowCount()+1;i++)
            {
                for(int j = 1;j<model->columnCount()+1;j++)
                {
                    QAxObject *Range = worksheet->querySubObject("Cells(int,int)", i+1, j);
                    // 获取对应单元格的数据
                    QModelIndex index = model->index(i-1, j-1);
                    QStandardItem *item = model->itemFromIndex(index);

                    // 如果你想获取显示的字符串，可以使用下面的代码
                    QString data = item->text();
                    Range->dynamicCall("SetValue(const QString &)",item->data(Qt::DisplayRole).toString());
                }
            }
            workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(filePath));//保存至filepath
            workbook->dynamicCall("Close()");//关闭工作簿
            excel->dynamicCall("Quit()");//关闭excel
            delete excel;
            excel=NULL;
            QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("导出成功啦！！！"));
            qDebug().noquote() << QStringLiteral("导出成功啦！！！");
        } else {
            QMessageBox::critical(nullptr, QStringLiteral("提示"), QStringLiteral("导出文件名不能为空！"));
        }
    } else {
        QMessageBox::critical(nullptr, QStringLiteral("提示"), QStringLiteral("待导出的数据为空"));
    }
}

// 导出测试
//void MainWindow::exportTestSubjectExel()
//{
//    QString filePath=QFileDialog::getSaveFileName(this,tr("Save"),".",tr(" (*.xlsx)"));
//    QStringList headers;
//    headers << QStringLiteral("表头1") << QStringLiteral("表头2") << QStringLiteral("表头3") << QStringLiteral("表头4") << QStringLiteral("表头5") ;
//    int col = headers.size();
//    int row = 6;
//    QList<QList<QString>> dataAll;
//    for (int i = 0; i < row; i++) {
//        QList<QString> inLst;
//        for (int j = 0; j < col; j++) {
//            inLst.append(QString::number(i) + QString::number(j));
//        }
//        dataAll.append(inLst);
//    }

//    QAxObject excel("Excel.Application");						  //加载Excel驱动
//    excel.dynamicCall("SetVisible (bool Visible)", "false");	  //不显示窗体
//    excel.setProperty("DisplayAlerts", true);					  //不显示任何警告信息。如果为true那么在关闭是会出现类似“文件已修改，是否保存”的提示

//    QAxObject *workBooks = excel.querySubObject("WorkBooks");	  //获取工作簿集合
//    workBooks->dynamicCall("Add");								  //新建一个工作簿
//    QAxObject *workBook = excel.querySubObject("ActiveWorkBook"); //获取当前工作簿
//                                                                  //QAxObject *workBook = excel.querySubObject("Open(QString&)", filePath); //获取当前工作簿
//    QAxObject *workSheet = workBook->querySubObject("Sheets(int)", 1); //设置为 获取第一页 数据

//    // 大标题行
//    QAxObject *cell;
//    cell = workSheet->querySubObject("Cells(int,int)", 1, 1);
//    cell->dynamicCall("SetValue(const QString&)", "excel导出示例");
//    cell->querySubObject("Font")->setProperty("Size", 11);
//    // 合并标题行
//    QString cellTitle;
//    cellTitle.append("A1:");
//    cellTitle.append(QChar(col - 1 + 'A'));
//    cellTitle.append(QString::number(1));
//    QAxObject *range = workSheet->querySubObject("Range(const QString&)", cellTitle);
//    range->setProperty("WrapText", true);
//    range->setProperty("MergeCells", true);
//    range->setProperty("HorizontalAlignment", -4108);
//    range->setProperty("VertivcalAlignment", -4108);

//    // 行高
//    workSheet->querySubObject("Range(const QString&)", "1:1")->setProperty("RowHeight", 30);

//    //列标题
//    QString lastCars = QChar('A');
//    for (int i = 0; i < col; i++)
//    {
//        // excel表格 A:A第一列到第一列,B:B第二列到第二列
//        // A B C D...X Y Z AA AB AC...AX AY AZ BA BB BC...
//        QString columnName;
//        QString cars;
//        if (i < 26) {
//            // 列数少于26个字母A B C D...X Y Z
//            cars = QChar(i + 'A');
//        } else {
//            // 列数大于26个字母 AA AB AC...AX AY AZ BA BB BC...
//            cars = QChar(i / 26 - 1 + 'A');
//            cars.append(QChar(i % 26 + 'A'));
//        }
//        columnName = cars + ":" + cars;
//        lastCars = cars;
//        // 有大标题，列标题从第二行开始("Cells(int, int)", 2, i+1)
//        // 无大标题，列标题从第一行开始("Cells(int, int)", 1, i+1)
//        QAxObject *col = workSheet->querySubObject("Columns(const QString&)", columnName);
//        QAxObject *cell = workSheet->querySubObject("Cells(int, int)", 2, i+1);
//        cell->dynamicCall("SetValue(const QString&)", headers[i]);
//        cell->querySubObject("Font")->setProperty("Bold", true);
//        cell->querySubObject("Interior")->setProperty("Color", QColor(191, 191, 191));
//        cell->setProperty("WrapText", true);						//内容过多，自动换行
//        cell->setProperty("HorizontalAlignment", -4108);
//        cell->setProperty("VertivcalAlignment", -4108);
//    }

//    //处理数据
//    int curRow = 3;
//    foreach(QList<QString> inLst, dataAll) {
//        for (int j = 0; j < col; j++) {
//            // ("Cells(int, int)", row, col)单元格的行和列从开始
//            QAxObject *cell = workSheet->querySubObject("Cells(int, int)", curRow, j+1);
//            cell->dynamicCall("SetValue(const QString&)", inLst[j]);
//            QAxObject* border = cell->querySubObject("Borders");
//            border->setProperty("Color", QColor(0, 0, 0));		 //设置单元格边框色（黑色）
//        }
//        curRow++;
//    }

//    //保存至filepath，注意一定要用QDir::toNativeSeparators将路径中的"/"转换为"\"，不然一定保存不了。
//    workBook->dynamicCall("SaveAs(const QString&)", QDir::toNativeSeparators(filePath));
//    workBook->dynamicCall("Close()");	//关闭工作簿
//    excel.dynamicCall("Quit()");		//关闭excel
//    QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("导出成功啦！！！"));
//    qDebug().noquote() << QStringLiteral("导出成功啦！！！");
//}




//void MainWindow::importToExcel(const QString &filePath)
//{
//    QAxObject excel("Excel.Application");			                    //加载Excel驱动
//    excel.setProperty("Visible", false);			                    //不显示Excel界面，如果为true会看到启动的Excel界面
//    QAxObject *workBooks = excel.querySubObject("WorkBooks");
//    workBooks->dynamicCall("Open (const QString&)", filePath);			 // 打开指定文件

//    QAxObject *workBook = excel.querySubObject("ActiveWorkBook");
//    QAxObject *workSheet = workBook->querySubObject("Sheets(int)", 1);   //设置为 获取第一页 数据
//    QAxObject *usedRange = workSheet->querySubObject("UsedRange");
//    QAxObject *rows = usedRange->querySubObject("Rows");
//    int rowCount = rows->property("Count").toInt();                      //获取行数

//    QVariantList allEnvDataList = usedRange->dynamicCall("Value").toList();

//    QString lastId;

//    for (int i = 2; i < rowCount; i++) {
//        QList<QVariant> allEnvDataList_i = allEnvDataList[i].toList();
//        //insertTableDesign(allEnvDataList_i);   // 行数据
//        // allEnvDataList_i 为 QList<QVariant> 类型
//        // QVariant转为QString  allEnvDataList_i[3].toString();
//        // QString转为QVariant	QString(allEnvDataList_i[i]);
//    }
//    workBook->dynamicCall("Close(Boolean)", false);                      //关闭文件
//    excel.dynamicCall("Quit(void)");				                     //退出
//}

//QString strData;
//void MainWindow::on_pushButton_17_clicked()
//{
//    //首先我们需要创建一个文件选择对话框
//    QString curPash =QDir::currentPath(); //获取当前路径
//    QString dlgTitle="选择表格文件";
//    //xls和xlsx格式的文件都可以，xlsx兼容xls，注意每一种类型后面要加两个分号
//    QString filter="表格文件(*.xls *.xlsx);;xls文件(*.xls);;xlsx文件(*.xlsx);;所有文件(*.*)";
//    //创建文件选择对话框
//    QStringList fileList = QFileDialog::getOpenFileNames(this,dlgTitle,curPash,filter);
//    if(fileList.count()<1)
//        return;
//    for(int i = 0;i<fileList.count();i++)
//    {
//        //保存文件地址
//        strData = fileList.at(i);
//    }
//    //连接Excel控件
//    QAxObject excel("Excel.Application");
//    //不显示任何警告信息
//    excel.setProperty("Visible",false);
//    //获取工作簿集合
//    QAxObject *workbooks = excel.querySubObject("WorkBooks");
//    workbooks->dynamicCall("Open (const QString&)",str);
//    //获取活动工作簿
//    QAxObject *workbook = excel.querySubObject("ActiveWorkBook");
//    //获取工作表集合的工作表1，即sheet1
//    QAxObject *worksheet = workbook->querySubObject("Sheets(int)",1);
//    QAxObject *range; //获取cell的值
//    QString strVal="hull";
//    QStringList header;
//    //设置初始表格行列都为0
//    ui->tableWidget->setRowCount(0); //设置行数为0
//    ui->tableWidget->setColumnCount(0); //设置列数为0

//    int count =0;
//    for(int i = 1;i<row;i++)
//    {
//        //注意setRowCount里面的函数不是追加，而是总数，很多人最开始都把这个函数以为是总数，造成程序经常崩溃
//        ui->tableWidget->setRowCount(ui->tableWidget->rowCount()+1);
//        for(int j = 1;j<column;j++)
//        {
//            if(i == 1)
//            {
//                ui->tableWidget->setColumnCount(ui->tableWidget->columnCount()+1);
//                range = worksheet->querySubObject("Cells(int,int)",i,j); //获取cell的值
//                strVal = range->dynamicCall("Value2()").toString();
//                header<<strVal;
//                //设置表格头
//            }
//            else
//            {
//                probar->setValue(++count);
//                range = worksheet->querySubObject("Cells(int,int)",i,j); //获取cell的值
//                strVal = range->dynamicCall("Value2()").toString();
//                ui->tableWidget->setItem(i-2,j-1,new QTableWidgetItem(strVal));
//            }
//        }
//        if(i == 1)
//        {
//            ui->tableWidget->setHorizontalHeaderLabels(header);
//        }
//    }
//    ui->tableWidget->setRowCount(ui->tableWidget->rowCount()-1);
//    }
//}

